package com.ybg.share.core.report;

import com.bstek.ureport.definition.datasource.BuildinDatasource;
import org.springframework.jndi.JndiObjectFactoryBean;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * JNDI 类
 *
 * @author deament
 */
public class JNDIBuildinDatasource implements BuildinDatasource {

    String name;
    String jndiName;

    public JNDIBuildinDatasource(String name, String jndiName) {
        this.name = name;
        this.jndiName = jndiName;
    }
    public JNDIBuildinDatasource() {

    }

    @Override
    public String name() {
        return name;
    }

    @Override
    public Connection getConnection() {
        JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiName(getJndiName());
        jndiObjectFactoryBean.setResourceRef(true);
        jndiObjectFactoryBean.setProxyInterface(DataSource.class);
        try {
            DataSource db = jndiObjectFactoryBean.getJndiTemplate().lookup(getJndiName(), DataSource.class);
            return db.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getJndiName() {
        return jndiName;
    }

    public void setJndiName(String jndiName) {
        this.jndiName = jndiName;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
